<?php
namespace app\admin\controller;
use think\facade\Request;
use think\facade\Db;
use think\facade\Validate;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use app\admin\validate\Confirm;
class Admin
{
    public function doLogin()
    {
        $data=Request::post();
        // 获取POST请求数据
        if (isset($data['student_id'])) { 
            $student_id = $data['student_id'];
        }else{
            return json(['message'=>'无账号输入','code'=>400]);
        }
        if (isset($data['password'])) { 
            $password = $data['password'];
        }else{
            return json(['message'=>'无密码输入','code'=>400]);
        }
        $validate = new Confirm();
        // $validate = Validate::rule(['student_id' => 'require|mobile',]);
        // 查询数据库以查找用户
        // 检查用户名和密码是否已提交
        if (empty($student_id)) {
            return json(['message' => '请输入账号', 'code' => 400]);
        }
        
        $currentTime = time();
        $admin = DB::table('user')->where('student_id',$student_id)->find();
        if(!$admin){
            return json([
                'code' =>400,
                'message' =>'账号不存在,请联系管理员',
            ]);
        }
        if(!$admin['status']){
            return json([
                'code' =>400,
                'message' =>'账号被禁用,请联系管理员',
            ]);
        }
        if (Db::table('user')->where('student_id',$student_id)->value('password') == md5($password)) {
            // 用户验证成功，生成JWT
            $key = env('JWT_SECRET');
            $payload = [
                'iat' => $currentTime, // 签发时间
                'exp' => $currentTime + 3600, // 过期时间，这里设置为1小时后
                'data' => [
                    'adminId' => $admin['id'], // 用户ID
                    'student_id' => $admin['student_id'], // 用户名
                ],
            ];
            $userData=Db::name('user')->where('student_id',$student_id)->find();
            $username=$userData['username'];
            // 生成JWT
            $token = JWT::encode($payload, $key, 'HS256');
            // 返回JWT
            return json([
                'token' => $token,
                "expiresIn" => 3600,
                "data" => [
                    "adminId" => $admin['id'],
                    "username"=> $username,
                ],
                "message" => "登录成功",
                "code" => 200,
            ]);
        }else {
                return json([
                'message'=>'密码错误',
                'code'=>400
            ]);
        }
    }

    public function decodeToken()
    {
        $key =env('JWT_SECRET');
        // 从HTTP请求头中获取JWT令牌
        if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
            $authHeader =$_SERVER['HTTP_AUTHORIZATION'];
        }else{
            return json([
                'message'=>'未设置HTTP_AUTHORIZATION',
                'code'=>400
            ]);
        }
        $token = trim(explode(" ",$authHeader)[1]);
        if ($token) {
            try {
                // 解析令牌
                $decoded = JWT::decode($token, new Key($key, 'HS256'));
                // 从解码后的数据中提取userid
                // 使用提取的userid进行后续操作
                $aaaaData=(array) $decoded;
                $data=$aaaaData['data'];
                $data=(array)$data;
                $adminId=$data['adminId'];
                return json_encode([
                    'code' => 200,
                    'message' => 'Success',
                    'data' => [
                        'adminId' => $adminId
                    ]
                ]);
            } catch (\Firebase\JWT\ExpiredException $e) {
                // 令牌过期
                return 'Token expired';
            } catch (\Exception $e) {
                // 其他错误
                return 'Error: ' . $e->getMessage();
            }
        } else {
            // 令牌未提供
            return 'Token not provided';
        }
    }
}  


